//
//  MTNewMineVC.m
//  met
//
//  Created by 李晓俊 on 2019/6/4.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTNewMineVC.h"
#import "MTNewMineHeadView.h"
#import "MTNewMineCell.h"
#import "MTNewMineView.h"
#import "MTEditDataVC.h"
#import "MTTicketVC.h"
#import "MTNewMineTextView.h"
#import "MTNewEditQuestionVC.h"
#import "MTAngelVC.h"
#import "MTMapVC.h"
#import "MTMarkDetailVC.h"

#import <RSKImageCropper/RSKImageCropper.h>
@interface MTNewMineVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate,RSKImageCropViewControllerDelegate>
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic ,strong) UIAlertController *alert;

@property (nonatomic,strong) MTNewMineHeadView *headView;
@property (nonatomic,strong) MTNewMineTextView *textView;

@property (nonatomic, assign) UIView *background;//图片放大
@property (nonatomic, assign) UIImageView *browseImgView;//图片放大

@end


@implementation MTNewMineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self wr_setNavBarBackgroundAlpha:0];
    self.tableview = [[UITableView alloc] initWithFrame: CGRectMake(0, -NavHeight, kScreenWidth, self.view.frame.size.height +NavHeight) style:UITableViewStyleGrouped];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.view addSubview:self.tableview];
//    self.tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    self.tableview.backgroundColor = KBackColor;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dataArr = [NSMutableArray new];
    
    self.headView = [[MTNewMineHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 316)];
    self.tableview.tableHeaderView = self.headView;
    
    self.headView.shezhiChoose = ^(NSString *  num) {
        MTEditDataVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTEditDataVC");
        [self.navigationController pushViewController:vc animated:YES];
    };
    self.headView.qianbaoChoose  = ^(NSString *  num) {
        MTTicketVC *vc =  GetViewControllerInStoryboard(@"Mine", @"MTTicketVC");
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.headView.angleChoose  = ^(NSString *  num) {
//        MTTicketVC *vc =  GetViewControllerInStoryboard(@"Mine", @"MTTicketVC");
        MTAngelVC *vc = [[MTAngelVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    self.headView.dituChoose = ^(NSString * _Nonnull num) {
        MTMapVC *vc = [[MTMapVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.textView  = [[MTNewMineTextView alloc] initWithFrame:CGRectMake(0, kScreenHeight-94, kScreenWidth, 94)];
    [self.view addSubview:self.textView];
    
    self.headView.nameChoose = ^(NSString *  num) {
        self.textView.hidden = NO;
        [self.textView.nameTF becomeFirstResponder];
    };
    self.textView.hidden = YES;
    self.textView.nameTF.delegate = self;
    self.textView.sureChoose = ^(NSString *  name) {
        [self done];
    };
    self.headView.headImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headImageClick)];
    [self.headView.headImage addGestureRecognizer:tap];
    
    self.view.backgroundColor = KWhiteColor;
    self.tableview.backgroundColor = KWhiteColor;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    self.textView.hidden= YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    self.textView.hidden= YES;
    [self.textView.nameTF resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.textView.hidden= YES;
    [self.textView.nameTF resignFirstResponder];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    DLog(@"%f",self.tableview.contentOffset.y);
    float y = self.tableview.contentOffset.y;
    
    if (self.tableview.contentOffset.y <= -NavHeight) {
        self.tableview.bounces = NO;
        [self wr_setNavBarBackgroundAlpha:0];

    }
    else if (self.tableview.contentOffset.y >= -NavHeight){
        self.tableview.bounces = YES;
        float alpha = 1 - ( (0 - y)/NavHeight);
        [self wr_setNavBarBackgroundAlpha:alpha];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataArr.count == 0) {
        return 0;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MTNewMineCell *cell = [MTNewMineCell cellWithTableView:tableView];
    for (int i = 0; i < self.dataArr.count; i ++) {
        int x = i % 2;
        int y = i / 2;
        CGFloat wid  = (kScreenWidth-20-10)/2.0;
        MTNewMineView *v = [[MTNewMineView alloc] initWithFrame:CGRectMake(x*(wid+10)+5, (wid*4/3.0+100) * y, wid, wid*4/3.0 + 90)];
        [cell.bgView addSubview:v];
        
        UserStoryYinJiModel *model = [self.dataArr objectAtIndex:i];
        v.model = model;
        v.selectChoose = ^(UserStoryYinJiModel * dic) {
            if ([[NSString stringWithFormat:@"%@",dic.objectType]isEqualToString:@"1"]) {
                //印记
                [self getYinjiDetail:[NSString stringWithFormat:@"%@",dic.objectId]];
            }else {
                [self getStoryDetail:[NSString stringWithFormat:@"%@",dic.objectId]];
            }
        };
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int y = (self.dataArr.count - 1) / 2;
    CGFloat wid  = (kScreenWidth-20-10)/2.0;

    return (wid*4/3.0+100) * (y+1);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
   
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    return view;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏默认的背景颜色
    [self getUserInfo];
    [self getStory];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [UIApplication sharedApplication].statusBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    self.textView.hidden= YES;
    [self.textView.nameTF resignFirstResponder];
}
- (void)getUserInfo{
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            KUSER = data;
            NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [KUSER mj_keyValues];
            //             操作者将包含用户信息的数组arr持久化
            [userInfo setValue:dic forKey:@"userinfo"];
            //把值立即存进去,放置数据丢失
            [[NSUserDefaults standardUserDefaults]synchronize];
            [self.headView.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitMap]] placeholderImage:[UIImage imageNamed:@"男（未选中）"]];
//            if ([[NSString stringWithFormat:@"%@",KUSER.sex] isEqualToString:@"1"]) {
//                [self.headView.angelImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitImMin]] placeholderImage:[UIImage imageNamed:@"默认天使男"]];
//            }else {
//                [self.headView.angelImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitImMin]] placeholderImage:[UIImage imageNamed:@"默认天使女"]];
//            }

            [self.headView.dituImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.mapImage]] placeholderImage:[UIImage imageNamed:@"图层 36"]];
            
            self.headView.name.text = [NSString stringWithFormat:@"%@",KUSER.nickName];
            self.headView.chepiaoCount.text = [NSString stringWithFormat:@"%@",KUSER.ticket];
            self.textView.nameTF.text = [NSString stringWithFormat:@"%@",KUSER.nickName];

            [self.tableview reloadData];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findUserInfo];
}
- (void)getStory{
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    AccountService *acc = [AccountService getObject];
//    acc.httpRequestResultBlock = ^(id data,int code){
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (code == 1) {
//            self.dataArr = [NSMutableArray arrayWithArray:data];
//            if (self.dataArr.count > 0) {
//                NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
//                [dataUser setObject:@"1" forKey:@"fabu"];
//                [dataUser synchronize];
//            }
//            [self.tableview reloadData];
//        }else {
//            [self.view maketishiToast:data];
//        }
//    };
//    [acc findStoryByUsersId:KUSER.usersId];
    
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            self.dataArr = [NSMutableArray arrayWithArray:data];
            if (self.dataArr.count > 0) {
                NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
                [dataUser setObject:@"1" forKey:@"fabu"];
                [dataUser synchronize];
            }
            [self.tableview reloadData];
        }else {
            [self.view maketishiToast:data];
         }
    };
    [acc storyFindStoryAndIPByUsersId:[NSString stringWithFormat:@"%@",KUSER.usersId]];
}
- (void)getStoryDetail:(NSString *)storyId{
    [self.textView.nameTF resignFirstResponder];

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            NSMutableArray *ar = [NSMutableArray new];
             NSArray *arr = [data objectForKey:@"questionList"];
            for (NSDictionary *info in arr) {
                NSArray *answerList = [info objectForKey:@"answerList"];
                NSMutableDictionary *dic = [NSMutableDictionary new];
                dic[@"question"] = [info objectForKey:@"questionText"];
                dic[@"answerfail"] = [info objectForKey:@"remarks"];
                
                for (int i = 0; i < answerList.count; i++) {
                    NSDictionary *answerInfo = [answerList objectAtIndex:i];
                    if ([[NSString stringWithFormat:@"%@",[answerInfo objectForKey:@"resultType"]]isEqualToString:@"1"]) {
                        dic[@"answer2"] = [answerInfo objectForKey:@"answerText"];
                    }else {
                        dic[@"answer1"] = [answerInfo objectForKey:@"answerText"];
                    }
                dic[@"isLike"] = @"1";

                }
                [ar addObject:dic];
            }
            
            //            MTEditQuestionVC *vc = [[MTEditQuestionVC alloc] init];
            MTNewEditQuestionVC *vc = [[MTNewEditQuestionVC alloc] init];
            
            vc.dataArr = ar;
            vc.storyId = [NSString stringWithFormat:@"%@",[data objectForKey:@"storyId"]];
            vc.storyVersion = [NSString stringWithFormat:@"%@",[data objectForKey:@"storyVersion"]];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findStoryByStoryId:storyId];
}
- (void)getYinjiDetail:(NSString *)storyId{
    [self.textView.nameTF resignFirstResponder];

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            MTMarkDetailVC *vc = [[MTMarkDetailVC alloc] init];
            vc.model = data;
            vc.isLook = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc imprintFind:storyId];
}


//点击完成
- (void)done {
    if (self.textView.nameTF.text.length == 0) {
        [[UIApplication sharedApplication].keyWindow maketishiToast:@"请先输入昵称"];
        return;
    }
    self.textView.hidden= YES;
    [self.textView.nameTF resignFirstResponder];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [self getUserInfo];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc updUsersInfoNickName:self.textView.nameTF.text];
    
}

- (void)headImageClick {
    //头像
    if (!self.alert) {
        self.alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *paizhao =[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self paizhao];
        }];
        [paizhao setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:paizhao];
        UIAlertAction *xiangce = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self xiangce];
        }];
        [xiangce setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:xiangce];
        UIAlertAction *big = [UIAlertAction actionWithTitle:@"查看大图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self bigImage];
        }];
        [big setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:big];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancle setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:cancle];
    }
  
    [self presentViewController:self.alert animated:true completion:nil];
}
- (void)paizhao {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //        picker.allowsEditing = YES; //可编辑
    //判断是否可以打开照相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        NSLog(@"没有摄像头");
    }
}
- (void)xiangce {
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    //相册
    //        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //图库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    //导航栏title颜色
    NSMutableDictionary *textAttr = [NSMutableDictionary dictionary];
    textAttr[NSForegroundColorAttributeName] = KBlackColor;
    picker.navigationBar.titleTextAttributes = textAttr;
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [picker.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    //设置右侧取消按钮的字体颜色
    picker.navigationBar.tintColor = KMainColor;
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *origin = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImagePickerControllerEditedImage
    //    self.headImage.image = origin;
//    [picker dismissViewControllerAnimated:YES completion:nil];
    
    RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:origin cropMode:RSKImageCropModeSquare];
    imageCropVC.delegate = self;
    [picker pushViewController:imageCropVC animated:NO];

//    [self.navigationController pushViewController:imageCropVC animated:YES];
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    AccountService *acc = [AccountService getObject];
//    acc.httpRequestResultBlock = ^(id data,int code){
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (code == 1) {
//            [self getUserInfo];
//        }else {
//            [self.view maketishiToast:data];
//        }
//    };
//    [acc updUsersInfo:[NSString stringWithFormat:@"%@",KUSER.usersId] portraitMap:origin];
}

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller
{
    [controller dismissViewControllerAnimated:YES completion:nil];

//    [self.navigationController popViewControllerAnimated:YES];
}

// The original image has been cropped. Additionally provides a rotation angle used to produce image.
- (void)imageCropViewController:(RSKImageCropViewController *)controller
                   didCropImage:(UIImage *)croppedImage
                  usingCropRect:(CGRect)cropRect
                  rotationAngle:(CGFloat)rotationAngle
{
    self.headView.headImage.image = croppedImage;
    [controller dismissViewControllerAnimated:YES completion:nil];

//    [self.navigationController popViewControllerAnimated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [self getUserInfo];
        }else {
            [self.view maketishiToast:data];
            [controller dismissViewControllerAnimated:YES completion:nil];
        }
    };
    [acc updUsersInfo:[NSString stringWithFormat:@"%@",KUSER.usersId] portraitMap:croppedImage];
    
}

// The original image will be cropped.
- (void)imageCropViewController:(RSKImageCropViewController *)controller
                  willCropImage:(UIImage *)originalImage
{
    // Use when `applyMaskToCroppedImage` set to YES.
}

//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//头像放大
- (void)bigImage{
    //创建一个黑色背景 //初始化一个用来当做背景的View。
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _background = bgView;
    [bgView setBackgroundColor:[UIColor colorWithRed:0/250.0 green:0/250.0 blue:0/250.0 alpha:1.0]];
    //[self.view addSubview:bgView];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView]; //创建显示图像的视图
    //初始化要显示的图片内容的imageView
    UIImageView *browseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NavHeight)];
    browseImgView.contentMode = UIViewContentModeScaleAspectFit;
    self.browseImgView = browseImgView;
    //要显示的图片，即要放大的图片
    [_browseImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitMap]]];
    
    [bgView addSubview:browseImgView]; browseImgView.userInteractionEnabled = YES; //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)]; [browseImgView addGestureRecognizer:tapGesture];
    [self shakeToShow:bgView];//放大过程中的动画
}
//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.3; NSMutableArray *values = [NSMutableArray array]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]]; animation.values = values; [aView.layer addAnimation:animation forKey:nil];
}
-(void)closeView{
    [_background removeFromSuperview];
}
@end
